/*
*场景
*/
package v1

import (
	"bc/dao"
	"bc/service"
	"bc/util"
	"bc/util/library/zstack"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"strconv"
	"time"
)

type scene struct {

}
func (t *scene)Create(c *gin.Context){
	var (
		res_byte []byte
		err error
	)

	res_byte,err = ioutil.ReadAll(c.Request.Body)
	defer c.Request.Body.Close()

	if err != nil {
		c.JSON(200,gin.H{
			"code":500,
			"msg":"error",
			"data":err.Error(),
		})
		return
	}

	data := make(map[string]interface{})
	err = json.Unmarshal(res_byte,&data)

	if err != nil {
		c.JSON(200,gin.H{
			"code":500,
			"msg":"invalid character",
			"data":err.Error(),
		})
		return
	}
	img := data["img"].(string)
	//上传图片
	path := util.SaveToImage(img)
	//判读数据是否存在
	var scene dao.Scene
	if v,ok := data["topo"];ok{
		topo := v.(map[string]interface{})
		if v,ok := topo["nodes"];ok {
			n,err := json.Marshal(v)
			if err != nil {
				fmt.Println("json err:", err)
			}
			scene.Nodes = string(n)
		}
		if v,ok := topo["edges"];ok {
			e,err := json.Marshal(v)
			if err != nil {
				fmt.Println("json err:", err)
			}
			scene.Edges = string(e)
		}
	}
	//获取用户id
	scene.Uid = c.GetInt("uid")
	//if v,ok := data["num"];ok{
	//	scene.Num = uint8(v.(float64))
	//}
	if v,ok := data["scene"];ok{
		s := v.(map[string]interface{})
		if v,ok := s["scene_name"];ok{
			scene.Scene_name = v.(string)
		}
		if v,ok := s["dynamic_tag"];ok{
			scene.Dynamic_tag = v.(string)
		}
		if v,ok := s["scene_desc"];ok{
			scene.Scene_desc = v.(string)
		}
		if v,ok := s["scene_difficulty"];ok{
			scene.Scene_difficulty = v.(string)
		}
	}

	//scene.Num = uint8(data["num"].(float64))
	//scene.Scene_name = data["scene_name"].(string)
	//scene.Dynamic_tag = data["dynamic_tag"].(string)
	//scene.Scene_desc = data["scene_desc"].(string)
	//scene.Scene_difficulty = uint8(data["scene_difficulty"].(float64))
	topo := data["topo"].(map[string]interface{})
	l := len(topo)
	if l == 0{
		c.JSON(200,gin.H{
			"code":500,
			"msg":"",
			"data":"未填加拓扑数据",
		})
		return
	}
	scene.Num = uint8(l)
	scene.Img_url = path
	scene.C_time = time.Now().Unix()
	id,err := scene.Create()
	if err != nil {
		fmt.Println(err)
	}

	//num := data["num"].(float64)//当前自增id标识符

	//场景详细信息
	//scene := data["scene"].(map[string]interface{})

	//场景名称
	//scene_name := scene["scene_name"]
	////场景难度
	//difficu := scene["scene_difficulty"]
	//desc := scene["scene_desc"]
	//区域uuid，一期暂时创建在此
	//zone_uuid := "53349478546441128bcc54977482d594"

	//集群uuid
	cluster_uuid := "0bc9ed76451c4d928d15b99599c572b5"




	nodes := topo["nodes"].([]interface{})
	//edges := data["edges"].([]interface{})
	for _,v := range nodes{

		nv := v.(map[string]interface{})
		if nv["jiedian"] != nil{

			jiedian := nv["jiedian"].(map[string]interface{})

			//jd_type := jiedian["type"].(string)
			act := jiedian["act"].(string)
			//bj_id := jiedian["bj_id"].(float64)
			var bj_id float64
			if v,ok := jiedian["bj_id"];ok{
				bj_id = v.(float64)
			}else{
				continue
			}

			//获取镜像uuid，计算规格uuid
			//row := dao.SenceDao.FirstById(bj_id)

			////创建二层网络
			//l2_map := make(map[string]interface{})
			//l2_map["params"] = make(map[string]interface{})
			//l2_map["params"].(map[string]interface{})["name"] = act
			//l2_map["params"].(map[string]interface{})["description"] = ""
			//l2_map["params"].(map[string]interface{})["zoneUuid"] = zone_uuid
			//l2_map["params"].(map[string]interface{})["physicalInterface"] = "eth0"
			//l2_map["systemTags"] = [...]string{}
			//l2_map["userTags"] = [...]string{}
			//res_byte,err = json.Marshal(l2_map)
			//
			//if err != nil {
			//	c.JSON(200,gin.H{
			//		"code":500,
			//		"msg":"err",
			//		"data":err.Error(),
			//	})
			//	return
			//}
			//
			//l2vlan_call_back,err := zstack.NetWork.CreateL2NoVlanNetwork(string(res_byte))
			//if err != nil {
			//	continue
			//}
			//
			//l2_data := map[string]interface{}{}
			//
			//err = json.Unmarshal([]byte(l2vlan_call_back),&l2_data)
			//
			//if err != nil {
			//	fmt.Println([]byte(l2vlan_call_back))
			//	break
			//}
			//
			////zstack返回的二层网络信息
			//inv := map[string]interface{}{}
			//for{
			//
			//	res,err := util.Curl.Url(l2_data["location"].(string)).GET()
			//	if err != nil {
			//		fmt.Println(err)
			//		break
			//	}
			//
			//	l2_res := map[string]interface{}{}
			//	err = json.Unmarshal([]byte(res),&l2_res)
			//	if err != nil {
			//		break
			//	}
			//
			//	if v,ok := l2_res["error"];ok{
			//		//写入日志
			//		fmt.Println(v)
			//		break
			//	}
			//	v, ok := l2_res["inventory"]
			//	if ok {
			//		inv = v.(map[string]interface{})
			//		break
			//	}
			//
			//}
			//
			////创建三层网络
			//l3_map := map[string]interface{}{}
			//l3_map["params"] = make(map[string]interface{})
			//l3_map["params"].(map[string]interface{})["name"] = act
			//l3_map["params"].(map[string]interface{})["type"] = "L3BasicNetwork"
			////inv["uuid"]
			//l3_map["params"].(map[string]interface{})["l2NetworkUuid"] = "aaafe537e9fb40d788ed79b8b097686d"
			//l3_map["params"].(map[string]interface{})["category"] = "Private"
			//l3_map["params"].(map[string]interface{})["system"] = false
			//
			//l3_str,err := json.Marshal(l3_map)
			//if err != nil {
			//	fmt.Println("三层网络json数据错误")
			//	break
			//}
			//l3_res_str , err := zstack.NetWork.CreateL3Network(string(l3_str))
			//l3_cb := map[string]interface{}{}
			//
			//err = json.Unmarshal([]byte(l3_res_str),&l3_cb)
			//
			//if err != nil {
			//	fmt.Println("三层网络反序列化")
			//	break
			//}
			//l3_inv := make(map[string]interface{})
			//创建二层VXLAN网络
			l2Uuid := service.L2Net.CreateL2VxlanNetwork("d0eb54fc52e8471d8b739e00e6ddafeb","Test-Net", "Test","53349478546441128bcc54977482d594", id)
			//l2Uuid := "3e1dff80409e4c548a59b34e4889457c"
			if l2Uuid == "" {
				break
			}
			//l3Uuid := service.L3Net.CreateL3Network(act,l2Uuid,"Private")
			l3Uuid := service.L3Net.CreateL3Network(act,l2Uuid,"Private")
			if l3Uuid == "" {
				break
			}

			dnsStr := "8.8.8.8"
			dns := zstack.DNS{}
			dns.AddDNS(dnsStr,l3Uuid)
			ip := zstack.IP{}
			ip.AddIPRanges("Test-IP-Range","192.168.3.10","192.168.3.250","255.255.255.0","192.168.3.1", l3Uuid)

			//for{
			//	l3_res,err := util.Curl.Url(l3_cb["location"].(string)).GET()
			//	if err != nil {
			//		fmt.Println(err)
			//		break
			//	}
			//
			//	l3_res_d := map[string]interface{}{}
			//	err = json.Unmarshal([]byte(l3_res),&l3_res_d)
			//	if err != nil {
			//		break
			//	}
			//
			//	if v,ok := l3_res_d["error"];ok{
			//		//写入日志
			//		fmt.Println(v)
			//		break
			//	}
			//	v, ok := l3_res_d["inventory"]
			//	if ok {
			//		l3_inv = v.(map[string]interface{})
			//		break
			//	}
			//}
			jd_type := jiedian["type"].(string)
			//网关，路由器，交换机  开启二层网络
			if jd_type == "wg" || jd_type == "lyq" || jd_type == "jhj" || jd_type == "yzj"{
				var bj = dao.Bj{}
				err, bjImgAndIns := bj.ImgAndInsUUid(int(bj_id))
				vm := make(map[string]interface{})
				vm["params"] = make(map[string]interface{})
				vm["params"].(map[string]interface{})["name"] = act
				vm["params"].(map[string]interface{})["instanceOfferingUuid"] = bjImgAndIns.InsUUId
				//vm["params"].(map[string]interface{})["instanceOfferingUuid"] = "6352ac45567b4f5f9a773f8538f33b73"
				//vm["params"].(map[string]interface{})["imageUuid"] = "789ae4613fa52c7caed18c3cb34dc1a7"
				vm["params"].(map[string]interface{})["imageUuid"] = bjImgAndIns.ImgUUId
				fmt.Println(vm)
				l3net := make([]string,0)
				//l3net = append(l3net,l3_inv["uuid"].(string))
				l3net = append(l3net,l3Uuid)

				vm["params"].(map[string]interface{})["l3NetworkUuids"] = l3net

				vm["params"].(map[string]interface{})["clusterUuid"] = cluster_uuid
				vm["params"].(map[string]interface{})["strategy"] = "InstantStart"
				fmt.Println(vm)
				fmt.Println(l3net)
				byte,_ := json.Marshal(vm)
				node,_ := json.Marshal(v)
				sceneNode := dao.SceneNode{Scene_id: id,Date: string(node)}
				snId := sceneNode.Create()

				str,err := zstack.VM.Create(string(byte),snId,scene.Uid)
				if err != nil {
					fmt.Println(err.Error())
					break
				}
				var errlog service.Scene_errlog
				errlog.CreateLog(str)
			}

		}

	}

	c.JSON(200,gin.H{
		"code":200,
		"msg":"创建成功",
		"data":id,
	})

}
// @Summary 场景列表数据
// @Description Get JSON
// @Tags 场景管理
// @Param scene_name query string false "场景名称"
// @Param scene_difficulty query string false "场景难度"
// @Param num query string false "数量"
// @Param uid query string false "用户id"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} util.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/scene [get]
// @Security
func (t *scene)Find(c *gin.Context) {
	var data dao.Scenes
	var err error
	var pageSize = 10
	var pageIndex = 1

	size := c.Request.FormValue("pageSize")
	if size != "" {
		pageSize = util.StrToInt(err, size)
	}

	index := c.Request.FormValue("pageIndex")
	if index != "" {
		pageIndex = util.StrToInt(err, index)
	}

	numStr := c.Request.FormValue("num")
	if numStr != "" {
		num := util.StrToInt(err, numStr)
		data.Num = uint8(num)
	}
	uid := c.Request.FormValue("uid")
	if uid != "" {
		data.Uid = util.StrToInt(err, uid)
	}
	sceneDifficulty := c.Request.FormValue("scene_difficulty")
	if sceneDifficulty != "" {
		data.Scene_difficulty = sceneDifficulty
	}
	data.Scene_name = c.Request.FormValue("scene_name")
	result, count, err := data.GetPage(pageSize, pageIndex)
	util.HasError(c, err, "", -1)

	var mp = make(map[string]interface{}, 3)
	mp["list"] = result
	mp["count"] = count
	mp["pageIndex"] = pageIndex
	mp["pageSize"] = pageSize
	util.PageOK(c, result, count, pageIndex, pageSize, "")

}
// @Summary 场景列表数据
// @Description Get JSON
// @Tags 场景管理
// @Param sc_id path string true "主键id"
// @Success 200 {object} util.Response "{"code": 200, "data": [...]}"
// @Router /api/v1/scene/{sc_id} [get]
// @Security
func (t *scene)First(c *gin.Context)  {
	var Scene dao.Scene
	Scene.Sc_id, _ = strconv.Atoi(c.Param("sc_id"))
	result, err := Scene.Get()

	util.HasError(c, err, "抱歉未找到相关信息", 404)

	var res util.Response
	res.Data = result

	c.JSON(http.StatusOK, res.ReturnOK())
}
/**
	删除场景
 */
func (t *scene)Delete(c *gin.Context)  {
	scId := c.Param("sc_id")
	if scId == "" {
		util.HasError(c, nil, "抱歉未找到相关信息", 404)
	}
	id, _ := strconv.Atoi(scId)
	var sceneNode dao.SceneNode
	sceneNode.Scene_id = id
	nodes, err := sceneNode.FindSceneId()
	if err == nil {
		//util.HasError(c, err, "抱歉未找到相关信息", 404)
		for _,v := range nodes {
			zstack.VM.Delete(v.Uuid,"")
		}
	}

	netUuids,err := dao.L2Net.FindBySid(id)
	if err == nil {
		for _,v := range netUuids {
			zstack.NetWork.Delete(v.Uuid,"")
		}
	}
	var Scene dao.Scene
	Scene.Sc_id = id
	err = Scene.Delete()
	if err != nil {
		util.HasError(c, err, "抱歉未找到相关信息", 400)
	}
	var res util.Response
	res.Msg = "删除成功"
	c.JSON(http.StatusOK, res.ReturnOK())
}
var Scene = &scene{}